/**
 * UI 数据列表控件
 * @author wyajun[wyajun@slof.com]
 */
function DataGrid(o){
	this.editor = o;
	this.hiddenColumns = null;
	this.fieldColumns = null;
	this.id = null;
}
/**
 * 给某行的某个字段赋值
 * @param {Object} rownum
 * @param {Object} field
 * @param {Object} value
 */
DataGrid.prototype.setValue= function(rownum,field,value){
	if(rownum && field){
		var grid = jQuery.data(jQuery("#"+this.id)[0], "datagrid").grid;//
		var dataTable = jQuery("#"+this.id);
		var sch = "tr[datagrid-row-index=" + (parseInt(rownum)-1) + "]";	
		var submitTrs1 = jQuery(".datagrid-view1 .datagrid-body "+sch,grid);
		var res = [];
		var flg = true;
		submitTrs1.each(function(){
			var fields  = jQuery(this).find("input[submitName],textarea[submitName]");
			fields.each(function(){
				if(field == jQuery(this).attr("submitName")){
					jQuery(this).attr("value",value);
					flg = false;
					return false;
				}
			});
		});
		if(flg){
			var submitTrs2 = jQuery(sch,dataTable);
			submitTrs2.each(function(i){
				var fields  = jQuery(this).find("input[submitName],textarea[submitName]");
				fields.each(function(){
					if (field == jQuery(this).attr("submitName")) {
						jQuery(this).attr("value",value);
						return false;
					}
				});
			});	
		}
	}
} 
/**
 * 获取数据表格的json数据
 */
DataGrid.prototype.getTableData = function(rownum){
	var grid = jQuery.data(jQuery("#"+this.id)[0], "datagrid").grid;//
	var dataTable = jQuery("#"+this.id);
	var sch = "tr[datagrid-row-index"
	if(rownum){
		sch = sch + "=" + (parseInt(rownum)-1) + "]";
	} else {
		sch = sch + "]";
	}
	
	var submitTrs1 = jQuery(".datagrid-view1 .datagrid-body "+sch,grid);
	var res = [];
	submitTrs1.each(function(){
		var fields  = jQuery(this).find("input[submitName],textarea[submitName]");
		var obj = {};
		fields.each(function(){
			obj[jQuery(this).attr("submitName")] = jQuery(this).attr("value");
		});
		res.push(obj);
	});
	var submitTrs2 = jQuery(sch,dataTable);
	submitTrs2.each(function(i){
		var obj = res[i];
		var fields  = jQuery(this).find("input[submitName],textarea[submitName]");
		fields.each(function(){
			obj[jQuery(this).attr("submitName")] = jQuery(this).attr("value");
		});
	});
	return res;
}


/**
 * 初始化数据列表
 */
DataGrid.prototype.onReady = function(){
    var $editor = jQuery(this.editor);
	var options = new Object();
	//nowrap：换行
	options.nowrap = false;
	//斑马色
	options.striped = true;
	//数据标识
	options.pagination = false;
	//选中行
	options.singleSelect = true;
	//
	//id;标识
	var id = $editor.attr("id");
	this.id = id;
	//数据列表宽度；不存在则充满父容器
	var width = $editor.attr("width");
	if(width && jQuery.trim(width) != ""){
		options.width=parseInt(width);
	}
	//数据列表高度度，不存在则充满父容器
	var height = $editor.attr("height");
	if(height && jQuery.trim(height) != ""){
		options.height=parseInt(height);
	}
	var data = $editor.attr("data");
	if(data){
		data = eval("("+ data +")")
	} else {
		data = [];
	}
	//rownumbers;是否显示行号
	options.rownumbers=true;
	var columns = [];
	var hidden = [];
	//确定数据列表的表头
	var $trs = $editor.find("tr");
	$trs.each(function(i){
		var $tr = jQuery(this);
		columns[i] = [];
		var $tds = $tr.find(">td");
		$tds.each(function(j){
			var $td = jQuery(this);
			var fieldObj = new Object();
			//title:数据列表头显示名称
			var title = $td.attr("title");
			if(title){
				fieldObj.title = title;
			}
			//field:数据列表头对应数据集合的属性名称
			var field = $td.attr("field");
			if(field){
				fieldObj.field = field;
			}
			//width:数据列表头宽度
			var width = $td.attr("width");
			if(width){
				fieldObj.width = width;
			}
			//rowspan:设置数据列表头跨几行
			var rowspan = $td.attr("rowspan");
			if(rowspan){
				fieldObj.rowspan = rowspan;
			}
			//colspan:设置数据列表头跨几列
			var colspan = $td.attr("colspan");
			if(colspan){
				fieldObj.colspan = colspan;
			}
			//align:数据列表对应列的排版方式align
			var align = $td.attr("align");
			if(align){
				fieldObj.align = align;
			} else {
				fieldObj.align = "center";
			}
			//数据源
			var data = $td.attr("data");
			if(data){
				fieldObj.data = eval("("+data+")");
			}
			//调用函数
			var excuteFn = $td.attr("excuteFn");
			if(excuteFn){
				fieldObj.excuteFn = excuteFn;
			}
			//textarea 行、列
			var areaCols = $td.attr("areaCols");
			if(areaCols){
				fieldObj.areaCols = areaCols;
			}
			var areaRows = $td.attr("areaRows");
			if(areaRows){
				fieldObj.areaRows = areaRows;
			}
			//permitType文档选择类型限定范围
			var permitType = $td.attr("permitType");
			if(permitType){
				fieldObj.permitType = permitType;
			}	
			//验证
			var validator = $td.attr("validator");
			if(validator){
				fieldObj.validator = validator;
			}				
			//类型
			var type = $td.attr("type");
			if(type){
				fieldObj.type = type;
				if("checkbox" == type){
					fieldObj.fieldType = "checkbox";
					fieldObj.checkbox = true;
				}
				if("hidden" == type){
					hidden.push(fieldObj);
					return true;
				}
			}
			columns[i].push(fieldObj);
		});
	});
	options.columns=columns;
	this.hiddenColumns = hidden;
	this.fieldColumns = columns;

	//删除子节点
	$editor.empty();
	//执行数据列表组件函数
	using('datagrid', function(){
		jQuery("#"+id).datagrid(options);	
		//增加hidden 列
		addHiddenColumns(id,hidden,data,0);
		//增加数据列
		addDataFieldColumns(id,columns,data,0);
		//绑定事件
		bindEvent(id);
		//产生增加删除行按钮
		createAddAndDelButton(id);
	});
	//产生增加删除行按钮
	function createAddAndDelButton(id){
		var grid = jQuery.data(jQuery("#"+id)[0], "datagrid").grid;
		var dataTable = jQuery("#"+id);
		var bdiv = jQuery(".datagrid-view1 .datagrid-header .datagrid-header-inner table tbody tr td .datagrid-header-rownumber",grid);
		jQuery("<img onmouseover=\"javascript:this.style.cursor='pointer'\" src=\""+easyloader.base+"themes/icons/edit_add.png\"/>").bind("click.datagrid",addRow).appendTo(bdiv);
		jQuery("<img onmouseover=\"javascript:this.style.cursor='pointer'\" src=\""+easyloader.base+"themes/icons/edit_remove.png\"/>").bind("click.datagrid",delRow).appendTo(bdiv);
		var headHeight = jQuery(".datagrid-view1 .datagrid-header",grid).height();
		if(headHeight < 35){
			jQuery(".datagrid-view1 .datagrid-header",grid).height(35);
			jQuery(".datagrid-view1 .datagrid-header table",grid).height(35);
			jQuery(".datagrid-view2 .datagrid-header",grid).height(35);
			jQuery(".datagrid-view2 .datagrid-header table",grid).height(35);			
		}
		function addRow(){
			var maxTr = jQuery("tbody tr[datagrid-row-index]:last",dataTable);
			var maxRowNum = maxTr.attr("datagrid-row-index");
			if(!maxRowNum){
				maxRowNum = "-1";
			}
			var dt = [new Object];
			addHiddenColumns(id,hidden,dt,(parseInt(maxRowNum)+1));
			//增加数据列
			addDataFieldColumns(id,columns,dt,(parseInt(maxRowNum)+1));	
			//绑定事件
			bindEvent(id);	
		}
		function delRow(){
			//删除行
			var flg = "0";//行选中标识
			jQuery("tbody tr td.datagrid-column-ck input[type=checkbox]",dataTable).each(function() {
				if (jQuery(this).attr("checked")) {
					var rowIndex = jQuery(this).parent().parent().parent().attr("datagrid-row-index");
					jQuery("tr[datagrid-row-index="+rowIndex+"]",grid).each(function(){
						jQuery(this).remove();
					});
					flg =  "1";
				}
			});	
			if(flg == "0"){
				return;
			}
			//更新行号:数据行
			jQuery("tbody tr[datagrid-row-index]",dataTable).each(function(rn){
				//数据行
				jQuery(this).attr("datagrid-row-index",rn);				
			});	
			//更新行号：序号行
			jQuery(".datagrid-view1 .datagrid-body table tbody tr[datagrid-row-index]",grid).each(function(rn){
				//数据行
				jQuery(this).attr("datagrid-row-index",rn);
				jQuery(this).find("td div").empty().append(rn+1);
			});	
			
		}
		
	}
	function bindEvent(id){
		var grid = jQuery.data(jQuery("#"+id)[0], "datagrid").grid;	
		var dataTable = jQuery("#"+id);
		jQuery(".datagrid-header .datagrid-header-check input[type=checkbox]", grid)
			.bind("click.datagrid", function(){
			//checkbox：全选、反全选（表头checkbox）
			if (jQuery(this).attr("checked")) {
				jQuery("tbody tr td.datagrid-column-ck input[type=checkbox]",dataTable).each(function() {
					if (!jQuery(this).attr("checked")) {
						//行变色
						var rowIndex = jQuery(this).parent().parent().parent().attr("datagrid-row-index");
						var tr = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex + "]", grid);
						
						tr.addClass("datagrid-row-selected");
						jQuery(this).attr("checked", true);
					}
				});
			} else {
				jQuery(".datagrid-body tr.datagrid-row-selected", grid)
						.removeClass("datagrid-row-selected");
				jQuery("tbody tr td.datagrid-column-ck input[type=checkbox]",dataTable).attr("checked", false);
			}
		});
		//每个checkbox
		jQuery("tbody tr td.datagrid-column-ck input[type=checkbox]",dataTable)	.each(function() {
			jQuery(this).bind("click.datagrid", function(){
				//行变色
				var rowIndex = jQuery(this).parent().parent().parent().attr("datagrid-row-index");
				if (jQuery(this).attr("checked")) {
					var tr = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex + "]", grid);
					var ck = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex
									+ "] .datagrid-cell-check input[type=checkbox]", grid);
					tr.addClass("datagrid-row-selected");
					ck.attr("checked", true);					
				} else {
					var tr = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex + "]", grid);
					var ck = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex
									+ "] .datagrid-cell-check input[type=checkbox]", grid);
					tr.removeClass("datagrid-row-selected");
					ck.attr("checked", false);
				}
			});
		});
		//行号点击事件
		jQuery(".datagrid-view1 div.datagrid-body div.datagrid-body-inner table tbody tr",grid).each (function(){
			//行号
			var rowIndex = jQuery(this).attr("datagrid-row-index");
			jQuery(this).bind("click.datagrid",function(){
				if(jQuery("tbody tr[datagrid-row-index="+rowIndex+"]",dataTable).find("input[type=checkbox]").attr("checked")){
					var tr = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex + "]", grid);
					tr.removeClass("datagrid-row-selected");
					jQuery("tbody tr[datagrid-row-index="+rowIndex+"]",dataTable).find("input[type=checkbox]").attr("checked",false);
				}else {
					var tr = jQuery(".datagrid-body tr[datagrid-row-index=" + rowIndex + "]", grid);
					tr.addClass("datagrid-row-selected");
					jQuery("tbody tr[datagrid-row-index="+rowIndex+"]",dataTable).find("input[type=checkbox]").attr("checked",true);
				}
			});
		});
	}
	function addDataFieldColumns(id, columns, data,rownum){
		var $tbody = jQuery("#"+id).find("tbody");	
		for(var i = 0,j = data.length;i < j;i ++){
			//数据行
			var $tr = jQuery("<tr datagrid-row-index=\""+ (rownum+i)+"\" class=\"datagrid-row-alt\"></tr>").appendTo($tbody);
			var fields = getColumnsFields(columns);
			for(var m = 0,n = fields.length;m < n;m ++){
				var col =  getFieldColumn(columns,fields[m]);
				var val = data[i][fields[m]];
				if(!val){
					val = "";
				}
				if(col){
					
					//列元素
					var $td = jQuery("<td class=\"datagrid-column-"+fields[m]+"\"></td>").appendTo($tr);
					//style
					var style = "width:" + (col.width) + "px;";
					style += "text-align:" + (col.align || "left");
					//数据列
					//style
					var tdhtml = [""];
					tdhtml.push("<div style=\""+style+"\" ")
					if (col.checkbox) {
						tdhtml.push("class=\"datagrid-cell-check ");
					} else {
						tdhtml.push("class=\"datagrid-cell ");
					}
					if(jQuery.data(jQuery("#"+id)[0], "datagrid").options.rownumbers){
						tdhtml.push("datagrid-cell-height ");
					}
					tdhtml.push("\" ></div>");
					//div
					var $tdDiv = jQuery(tdhtml.join("")).appendTo($td);
					$tdDiv.css({paddingLeft:'2px'});
					var divWidth = $tdDiv.width();
					//field html
					var type = col.type;
					if ("checkbox" == type) {
						var checkboxfield =  jQuery("<input vstype=\"checkbox\" type=\"checkbox\" value=\""+val+"\"/>").appendTo($tdDiv);
					} else if("openWindow" == type) {
						var $openWindowfield =  jQuery("<input vstype=\"openWindow\" type=\"text\" submitName=\""+ col.field+"\" value=\""+val+"\" style=\"width:"+(parseInt(divWidth)-20)+";\" readOnly />").appendTo($tdDiv);
						if(col.validator){
							$openWindowfield.attr("validator",col.validator);
							using('validatebox', function() {
						        $openWindowfield.validatebox({});
						    });							
						}
						var $openWindowImg = jQuery("<img vstype=\"openWindow\" onmouseover=\"javascript:this.style.cursor='pointer'\" src=\""+easyloader.base+"themes/icons/search.png\"/>").appendTo($tdDiv);
						$openWindowImg.bind("click.datagrid",{excuteFn:col.excuteFn,rownum:parseInt(rownum+i)+1},function(event){
							try{
								window[event.data.excuteFn](event.data.rownum);
							}catch(err){
							
							}
						});							
					} else if("date" == type) {
						var $datefield = jQuery("<input  vstype=\"date\" type=\"text\" submitName=\""+ col.field+"\" style=\"width:"+(divWidth)+";\" readOnly value=\""+val+"\" />").appendTo($tdDiv);
						if(col.validator){
							$datefield.attr("validator",col.validator);
							using('validatebox', function() {
						        $datefield.validatebox({});
						    });							
						}
						//时间控件参数对象
						var opt = new Object();
						//皮肤
						if(easytogo_theme){
							opt.skin = easytogo_theme;
						}
						//语言
						if(easytogo_locale){
							opt.lang = easytogo_locale.toLowerCase();
						}
						//
					    //日期格式,默认格式为 yyyy-MM-dd
					    opt.dateFmt = "yyyy-MM-dd";
						//class=\"Wdate\"
						$datefield.addClass("Wdate");
					    $datefield.bind("click",options,function(event){
					    	WdatePicker(opt);
					    });						
					} else if("textarea" == type) {
						var $textareafield = jQuery("<textArea vstype=\"textarea\" submitName=\""+ col.field+"\" style=\"width:"+(divWidth)+";\" ></textArea>").appendTo($tdDiv);
						if(col.areaCols){
							$textareafield.attr("cols",col.areaCols);
						}
						if(col.areaRows){
							$textareafield.attr("rows",col.areaRows);
						}
						if(col.validator){
							$textareafield.attr("validator",col.validator);
							using('validatebox', function() {
						        $textareafield.validatebox({});
						    });							
						}					
					} else if("text" == type) {
						var $textfield = jQuery("<input vstype=\"text\" type=\"text\" submitName=\""+ col.field+"\" value=\""+val+"\" style=\"width:"+(divWidth)+";\" />").appendTo($tdDiv);
						if(col.validator){
							$textfield.attr("validator",col.validator);
							using('validatebox', function() {
						        $textfield.validatebox({});
						    });							
						}	
					} else if("multiselect" == type) {
						
					} else if("file" == type) {
						if(val){
							var filePrit = "";
							if(val.indexOf(".") != -1){
								filePrit = val.substring(val.lastIndexOf(".")+1).toLowerCase();
							}
							var $afield = jQuery("<a href=\"javascript:void(0);\" icon=\"icon-"+filePrit+"\" plain=\"true\">"+val+"</a>").appendTo($tdDiv);
							using('linkbutton', function() {
								
								$afield.linkbutton({});			
								if(col.excuteFn){
									$afield.bind("click.datagrid",{excuteFn:col.excuteFn,rownum:parseInt(rownum+i)},function(event){
										try{
											window[event.data.excuteFn](event.data.rownum);
										}catch(err){
										
										}
									});
								}								
							});
						} else {
							var $filefield = jQuery("<div></div>").appendTo($tdDiv);
							$filefield.attr("vstype","file");
							$filefield.attr("name",col.field);
							$filefield.attr("width",divWidth-25);
							$filefield.attr("permitType",col.permitType);
						    using('filetext', function() {
						        $filefield.filetext({});
								if(col.validator){
									$filefield.find(".filetext-viewText").attr("validator",col.validator);
									using('validatebox', function() {
								        $filefield.find(".filetext-viewText").validatebox({});
								    });							
								}							
						    });
						}
					} else if("combobox" == type) {
						var opthtml = [""];
						if(col.data){
							 for (var k in col.data) {
							 	opthtml.push("<option value=\""+k+"\">"+col.data[k]+"</option>");
	       					 }	
						}
						var $selectdfield = jQuery("<select vstype=\"combobox\" name=\""+ col.field+"\" style=\"width:"+(divWidth)+";\" >"+opthtml.join("")+"</select>").appendTo($tdDiv);
						using('combobox', function() {
					        $selectdfield.combobox({});
							if(val){
								$selectdfield.combobox("setValue",val);
							}
					    });
						
					} else {
						$tdDiv.append(val);
					}					
				}
			}
		}
	}
	function addHiddenColumns(id,hiddenColumns,data,rownum){
		var grid = jQuery.data(jQuery("#"+id)[0], "datagrid").grid;//
		var $tbody = grid.find(".datagrid-body-inner").find("table").find("tbody");
		var html = [""];
		for(var i = 0,j = data.length;i < j;i ++){
			html.push("<tr datagrid-row-index=\""+ (rownum+i)+"\" class=\"datagrid-row-alt\"><td>");
			for(var m = 0,n = hiddenColumns.length;m < n;m ++){	
			var val = data[i][hiddenColumns[m].field];
			if(!val){
				val = "";
			}
				html.push("<input type=\"hidden\" submitName=\""+ hiddenColumns[m].field+"\" value=\""+val+"\" />");
			}
			html.push("<div class=\"datagrid-cell-rownumber datagrid-cell-height\">"+(rownum+i+1)+"</div></td>");
			html.push("</tr>")
		}
		$tbody.append(html.join(""));
	}
	function getColumnsFields(_columns) {
		if (_columns.length == 0) {
			return [];
		}
		function _3b(_3c, _3d, _3e) {
			var _3f = [];
			while (_3f.length < _3e) {
				var col = _columns[_3c][_3d];
				if (col.colspan && parseInt(col.colspan) > 1) {
					var ff = _3b(_3c + 1, _40(_3c, _3d), parseInt(col.colspan));
					_3f = _3f.concat(ff);
				} else {
					if (col.field) {
						_3f.push(col.field);
					}
				}
				_3d++;
			}
			return _3f;
		};
		function _40(_41, _42) {
			var _43 = 0;
			for (var i = 0; i < _42; i++) {
				var _44 = parseInt(_columns[_41][i].colspan || "1");
				if (_44 > 1) {
					_43 += _44;
				}
			}
			return _43;
		};
		var _45 = [];
		for (var i = 0; i < _columns[0].length; i++) {
			var col = _columns[0][i];
			if (col.colspan && parseInt(col.colspan) > 1) {
				var ff = _3b(1, _40(0, i), parseInt(col.colspan));
				_45 = _45.concat(ff);
			} else {
				if (col.field) {
					_45.push(col.field);
				}
			}
		}
		
		return _45;
	};	
	function getFieldColumn(columns, field){
		if (columns) {
			for (var i = 0; i < columns.length; i++) {
				var column = columns[i];
				for (var j = 0; j < column.length; j++) {
					var col = column[j];
					if (col.field == field) {
						return col;
					}
				}
			}
		}
		return null;
	}
}

